
#include <QCoreApplication>
#include <QTextStream>
#include <QDebug>

#include <QDBusConnection>
#include <QDBusInterface>
#include <QDBusReply>

#include <LogUtils>
#include <../DHelloWorld/DHelloWorld.h>


void messageCall()
{
    QDBusMessage msg = QDBusMessage::createMethodCall("com.qt.examples.DHelloWorld", "/", "com.qt.examples.DHelloWorld",
                       "Hello");

    msg << QString("Message: Hello World");

    QDBusMessage response = QDBusConnection::sessionBus().call(msg);

    if (response.type() == QDBusMessage::ReplyMessage)
    {
        LogUtils::log("Message: Hello is Called");
    }
}

void baseCall()
{
    QDBusInterface interface("com.qt.examples.DHelloWorld", "/", "com.qt.examples.DHelloWorld", QDBusConnection::sessionBus());;

    if (interface.isValid())
    {
        LogUtils::log("DHelloWorld: interface is valid.");
    }

    QDBusReply<void> reply = interface.call("Hello", "Base: Hello World");

    if (reply.isValid())
    {
        LogUtils::log("Base: Hello is Called.");
    }
}

void asyncCall()
{
    QDBusInterface interface("com.qt.examples.DHelloWorld", "/", "com.qt.examples.DHelloWorld", QDBusConnection::sessionBus());

    QDBusPendingCall async = interface.asyncCall("Hello", "Async: Hello World");
    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(async);

    QObject::connect(watcher, &QDBusPendingCallWatcher::finished, [](QDBusPendingCallWatcher * self)
    {

        if (!self->isError())
        {
            LogUtils::log("Async: Hello is Called");

        }
        else
        {
            LogUtils::log("Error: " + self->error().message());
        }

        self->deleteLater();
    });
}

void adapterCall()
{

}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // 消息调用
    messageCall();

    // 基本调用
    baseCall();

    // 异步调用
    asyncCall();

    // 适配器调用
    adapterCall();

    return a.exec();
}

